package com.bao.auth.server.biz.service.core.impl;

import com.bao.auth.entity.core.Org;
import com.bao.auth.server.biz.dao.core.OrgMapper;
import com.bao.auth.server.biz.service.core.OrgService;
import com.bao.databases.mybatis.conditions.Wraps;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * 业务实现类
 * 组织
 */
@Service
@Slf4j
public class OrgServiceImpl extends ServiceImpl<OrgMapper, Org> implements OrgService {
    @Override
    public List<Org> findChildren(List<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return Collections.emptyList();
        }
        //Mysql 全文索引
        String applySql = String.format(" MATCH(tree_path) AGAINST('%s' IN BOOLEAN MODE)", StringUtils.join(ids, " "));
        List<Org> list = super.list(Wraps.<Org>lbQ().in(Org::getId, ids).or(query -> query.apply(applySql)));
        return list;
    }

    @Override
    public boolean remove(List<Long> ids) {
        //还需要吧子节点也删除
        List<Org> list = this.findChildren(ids);
        List<Long> idList = list.stream().mapToLong(Org::getId).boxed().collect(Collectors.toList());
        return idList.isEmpty() ? true : super.removeByIds(idList);
    }
}
